package com.esms.service.impl;

import com.esms.dao.ScoreMapper;
import com.esms.dao.TKpiAssesmentMapper;
import com.esms.po.ScoreEntry;
import com.esms.po.TKpiAssesment;
import com.esms.service.IScoreService;
import com.esms.utils.DateUtil;
import com.esms.utils.week.DateWeekUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

@Service
public class ScoreServiceImpl implements IScoreService, ApplicationContextAware {

    @Autowired
    TKpiAssesmentMapper tKpiAssesmentMapper;

    private WebApplicationContext context;

    /**
     * calculateTotalScore
     * 计算总分并且填充到 t_kpi_assesment 表中,在无任何评价信息时无法生成
     */
    @Override
    public void calculateTotalScore() {
        String quarter = DateUtil.dateTimeDeal();
        ConcurrentHashMap<String, Float[]> scoreMap = new ConcurrentHashMap<>();
        CountDownLatch latch = new CountDownLatch(8);
        String[] scoreMappers = {"AAssessmentMapper", "FAssessmentMapper", "XWeekresultMapper", "TAssessmentMapper", "SAssessmentMapper", "QAssessmentMapper", "HAssessmentMapper", "GAssessmentMapper"};
        //首先灌入初始员工数据
        initializeData();
        Map<String, TKpiAssesment> infoMap = getKpiInfoMap();
        for (int i = 0; i < scoreMappers.length; i++) {
            int I = i;
            Runnable runnable = () -> {
                ScoreMapper sm = (ScoreMapper) context.getBean(scoreMappers[I]);
                List<ScoreEntry> scoreEntries = sm.listScore(quarter);
                scoreEntries.forEach(e -> {
                    if (!scoreMap.containsKey(e.getUserId())) {
                        scoreMap.put(e.getUserId(), new Float[9]);
                    }
                    scoreMap.get(e.getUserId())[I] = calculateScore(scoreMappers[I], e.getUserId(), e.getScore(), infoMap);
                });
                latch.countDown();
            };
            runnable.run();
            System.out.println();
        }


        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        scoreMap.forEach((k, v) -> {
            TKpiAssesment kpiAssesment = infoMap.get(k);
            if (v[5] == null) {
                if (kpiAssesment.gettDgsid() == 3 || kpiAssesment.gettDgsid() == 4) {
                    v[5] = 30.0F;
                }

            }
            ;
            if (v[6] == null) {
                if (kpiAssesment.gettDgsid() == 3 || kpiAssesment.gettDgsid() == 4) {
                    v[6] = 20.0F;
                } else if (kpiAssesment.gettDgsid() == 5) {
                    v[6] = 30.0F;
                }
            }
            Double sum = Arrays.stream(v).mapToDouble(e -> e != null ? e.doubleValue() : 0).sum();
            v[8] = sum.floatValue();
        });

        tKpiAssesmentMapper.updateScore(scoreMap);

    }

    @Override
    public void initializeData() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date currentTime = new Date();
        try {
            String qCreateQuarter = DateUtil.dateTimeDeal();
            String BeforeQuarter = DateWeekUtil.GetBeforeQuarterByDate(formatter.format(currentTime));
            tKpiAssesmentMapper.truncateData(BeforeQuarter);
            tKpiAssesmentMapper.initData(qCreateQuarter);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = (WebApplicationContext) applicationContext;
    }

    public Map<String, TKpiAssesment> getKpiInfoMap() {
        List<TKpiAssesment> tKpiAssesments = tKpiAssesmentMapper.listTPidAndTDgsidAndTEaccount();
        Map<String, TKpiAssesment> map = tKpiAssesments.stream().collect(Collectors.toMap(TKpiAssesment::gettEaccount, a -> a, (k1, k2) -> k1));
        return map;
    }

    /**
     * 根据当前计算分数的员工工号，查找归属不同的二级部门，按照规定的权重，计算最终成绩落表
     * {
     * "AAssessmentMapper",----同级评价分数表
     * "TAssessmentMapper",----上级对下级评价分数表
     * "SAssessmentMapper",----下级对上级评价分数表
     * "GAssessmentMapper" ----满意度分数表
     * <p>
     * "QAssessmentMapper",----工作业绩考核分数表
     * "HAssessmentMapper",----勤考核表分数表
     * <p>
     * "FAssessmentMapper",----加分项分数表
     * "XWeekresultMapper",----周纪实分数表
     * }
     **/
    public float calculateScore(String scoreFlag, String eAccount, float score, Map<String, TKpiAssesment> infoMap) {
        //这里面
//        score = score*9;//目前是写死的9，需要调整
        //这里面需要根据被评分人员的工号eAccount，
        //查出员工对应的上级部门和员工的职位信息(直接从最终结果表中查询即可，传入的score并进行相应的权重处理),
        // 根据scoreFlag打分类型(同级、上对下、下对上、满意度、周纪实等等)，进行不同的操作
        //然后根据下面的规则，去对号入座
        //score*相应的权重分数
//        TKpiAssesment tKpiAssesment;
//        tKpiAssesment = tKpiAssesmentMapper.getEmployeeByeAccount(eAccount);
        TKpiAssesment tKpiAssesment = infoMap.get(eAccount);
        Integer pid = tKpiAssesment.gettPid();
        Integer dgsid = tKpiAssesment.gettDgsid();
        Integer qscore = Integer.valueOf(tKpiAssesment.gettQscore());//业绩分数
        Integer hscore = Integer.valueOf(tKpiAssesment.gettHscore());//考勤分数


        /**1.1：审批服务组科长、科员考评流程和
         * 2.1：窗口进驻组科长、科员考评流程权重是一样的
         *
         * a.周纪实权重(不区分科长和科员)：20%：就是实际取出的分数乘以：score*0.2，因为周纪实前端打分是百分制
         *
         * b.民主评议权重(区分科长可科员)：10%*100=10分(满分)
         * 科长
         * •上级评议：40%*10=4分(满分)
         * •下级评议：30%*10=3分(满分)
         * •同级评议：30%*10=3分(满分)
         * 科员：
         * •上级评议：60%*20=12分(满分)
         * •同级评议：40%*20=8分(满分)
         *
         *  满意度：(不区分科长和科员)：20%*100=20分
         *
         * c.考勤：30%*100=30分
         *
         * d.工作业绩：20%*100=20分
         *
         * **/

        /**3.1综合保障组科长、科员考评流程
         * 周纪实权重：50%：就是分数要乘以：score*0.5，因为周纪实前端打分是百分制
         * 民主评议+满意度权重：20%*100=20分(满分)
         * 科长
         * •上级评议：40%*20=8分(满分)
         * •下级评议：30%*30=9分(满分)
         * •同级评议：30%*20=6分(满分)
         * 科员：
         * •上级评议：60%*20=12分(满分)
         * •同级评议：40%*20=8分(满分)
         * **/

        /**4.1 调研员考评流程
         * 周纪实权重：60%：就是分数要乘以：score*0.6，因为周纪实前端打分是百分制
         * 民主评议：40%*100=40分(满分)
         * **/

        /**4.2 副局长考评流程
         * 民主评议+满意度权重：70%*100=70分(满分)
         * 二级评议
         * •上级评议：60%*70=42分(满分)
         * •下级评议：40%*70=28分(满分)
         *
         * 分管科室综合评分：
         * 待定
         * **/


        //下面我用那个同级评价举个例子：
        if ("AAssessmentMapper".equals(scoreFlag)) {//同级评价分数表
            //需要判断当前员工的部门，和职位，调用上面不同的权重，进行分数重新计算

            if (dgsid == 3 || dgsid == 4) {//审批服务和窗口服务
                if (pid == 5) {//科员
                    score = score * 4;
                }
                if (pid == 4) {//科长
                    score = score * 3;

                }

            }
            if (dgsid == 5) { //综合保障
                if (pid == 5) {//科员

                    score = score * 8;
                }
                if (pid == 4) {//科长

                    score = score * 6;
                }
            }
            if (pid == 3) {//调研员
                score = (float) (score * 12);
            }


        } else if ("TAssessmentMapper".equals(scoreFlag)) {//上级对下级评价分数表
            if (dgsid == 3 || dgsid == 4) {//审批服务和窗口服务
                if (pid == 5) {//科员
                    score = score * 6;
                }
                if (pid == 4) {//科长
                    score = score * 4;

                }

            }
            if (dgsid == 5) { //综合保障
                if (pid == 5) {//科员

                    score = score * 12;
                }
                if (pid == 4) {//科长

                    score = score * 8;
                }
            }
            if (pid == 2) {//副局长
                score = score * 42;
            }
            if (pid == 3) {//调研员
                score = score * 16;
            }


        } else if ("SAssessmentMapper".equals(scoreFlag)) {//下级对上级评价分数表
            if (dgsid == 3 || dgsid == 4) {//审批服务和窗口服务

                if (pid == 4) {//科长
                    score = score * 3;

                }

            }
            if (dgsid == 5) { //综合保障

                if (pid == 4) {//科长

                    score = score * 6;
                }
            }
            if (pid == 2) {//副局长
                score = score * 28;
            }
            if (pid == 3) {//调研员
                score = score * 12;
            }


        } else if ("GAssessmentMapper".equals(scoreFlag)) {//满意度分数表
            if (dgsid == 3 || dgsid == 4) {//审批服务和窗口服务
                if (pid == 5) {//科员
                    score = (float) (score * 0.2);
                }
                if (pid == 4) {//科长
                    score = (float) (score * 0.2);

                }

            }


        } else if ("QAssessmentMapper".equals(scoreFlag)) {//工作业绩考核分数表
            if (dgsid == 3 || dgsid == 4 || dgsid == 5) {//审批服务和窗口服务
                if (pid == 5) {//科员
                    score = qscore - score;
                }
                if (pid == 4) {//科长
                    score = qscore - score;

                }

            }


        } else if ("HAssessmentMapper".equals(scoreFlag)) {//勤考核表分数表
            if (dgsid == 3 || dgsid == 4) {//审批服务和窗口服务
                if (pid == 5) {//科员
                    score = hscore - score;
                }
                if (pid == 4) {//科长
                    score = hscore - score;

                }

            }
            if (dgsid == 5) { //综合保障
                if (pid == 5) {//科员

                    score = hscore - score;
                }
                if (pid == 4) {//科长

                    score = hscore - score;
                }
            }

        } else if ("FAssessmentMapper".equals(scoreFlag)) {//加分项分数表

        } else if ("XWeekresultMapper".equals(scoreFlag)) {//周纪实分数表
            if (dgsid == 3 || dgsid == 4) {//审批服务和窗口服务
                if (pid == 4) {
                    score = (float) (score * 0.2);
                }//科长

                if (pid == 5) {
                    score = (float) (score * 0.2);

                }//科员
            }
            if (dgsid == 5) {   //综合保障
                if (pid == 4) {
                    score = (float) (score * 0.5);

                }//科长
                if (pid == 5) {
                    score = (float) (score * 0.5);

                }//科员
            }
            if (pid == 3) {//调研员
                score = (float) (score * 0.6);
            }


        }
//        System.out.println(score);
        return score;
    }
}
